package com.lzy.business.controller;

import com.lzy.base.apis.SysRoleServiceApi;
import com.lzy.base.apis.SysUserAdminServiceApi;
import com.lzy.base.constants.Constants;
import com.lzy.base.dtos.SysRoleDto;
import com.lzy.base.dtos.SysUserAdminDto;
import com.lzy.base.utils.UserUtil;
import com.lzy.common.apis.ShopServiceApi;
import com.lzy.common.apis.StoreServiceApi;
import com.lzy.common.constants.BusinessType;
import com.lzy.common.dtos.ShopDto;
import com.lzy.common.dtos.StoreDto;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.output.Result;
import com.lzy.framework.tools.kv.KvClient;
import com.lzy.goods.item.dtos.ItemCategoryDto;
import com.lzy.sms.apis.MsgCodeApi;
import com.lzy.sms.constants.BusiTypeEnum;
import com.lzy.sms.dtos.CodeDTO;
import com.lzy.sms.dtos.SendSmsDTO;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lc
 * @date 2017年1月1日 下午5:37:14
 */
public class BaseController {
    private static final Logger LOGGER = LoggerFactory
            .getLogger(BaseController.class);
    @Resource
    private KvClient kvClient;
    @Autowired
    private SysRoleServiceApi sysRoleServiceApi;
    @Autowired
    private SysUserAdminServiceApi sysUserAdminServiceApi;

    @Autowired
    private ShopServiceApi shopServiceApi;
    @Autowired
    private MsgCodeApi msgCodeApi;

    @Autowired
    StoreServiceApi storeServiceApi;

    public final static String CITY_CODE_SESSION_KEY = "_city_code_";

    public final static String SUCCESS = "success";
    public final static String FAILD = "faild";
    public final static String STATUS_SUCCESS = "success";
    public final static String STATUS_FAILD = "faild";

    public final static String SUCCESS_CODE = "0";
    public final static String FAILED_CODE = "-1";

    public void storeSession(String key, Object value) {
        SecurityUtils.getSubject().getSession().setAttribute(key, value);
    }

    /**
     * 解析参数:
     *
     * @param request
     **/
    public Map<String, Object> getParams(HttpServletRequest request) {
        Map<String, Object> params = new HashMap<>();
        Map<String, String[]> oldParams = request.getParameterMap();
        Iterator<Map.Entry<String, String[]>> entries = oldParams.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, String[]> entry = entries.next();
            String keyName = entry.getKey();
            // 将所有参数放入map中
            if (entry.getValue()[0] != null && !entry.getValue()[0].equals("")) {
                if ("begin".equals(keyName) || "rows".equals(keyName)) {
                    params.put(keyName, Integer.valueOf(entry.getValue()[0]));
                } else {
                    params.put(keyName, entry.getValue()[0]);
                }
            }
        }
        params.put("deptId", UserUtil.getCurrentUser().getDeptId());
        params.put("shopId", UserUtil.getCurrentUser().getShopId());
        params.put("companyId", UserUtil.getCurrentUser().getCompanyId());
        params.put("dataType", UserUtil.getCurrentUser().getDataType());
        return params;
    }

    private String getKeyName(String oldKeyName) {
        String[] oldKeyNames = oldKeyName.split("-");
        return oldKeyName.replace(oldKeyNames[0] + "-", "").trim();
    }

    protected String getErrorMsg(BindingResult bindingResult) {
        return bindingResult.getAllErrors().get(0).getDefaultMessage();
    }

    public SysUserAdminDto getCurrentUser() {
        SysUserAdminDto admin = (SysUserAdminDto) SecurityUtils.getSubject().getSession()
                .getAttribute(Constants.SYS_USER);
        Ensure.that(admin).isNotNull("-1");
        admin.setRoleIds(getLoginUserRoleIds());
        admin.setRoleNames(getLoginUserRoleNames());
        return admin;
    }

    public String[] getCurrentUserStr() {
        SysUserAdminDto admin;
        admin = (SysUserAdminDto) SecurityUtils.getSubject().getSession()
                .getAttribute(Constants.SYS_USER);
        Ensure.that(admin).isNotNull("-1");
        String[] strString = new String[5];
        strString[0] = admin.getId().toString();
        strString[1] = admin.getLoginName();
        strString[2] = admin.getRealName();
        strString[3] = getLoginUserRoleIds();
        strString[4] = getLoginUserRoleNames();
        return strString;
    }

    public String getLoginUserName() {
        SysUserAdminDto admin = (SysUserAdminDto) SecurityUtils.getSubject().getSession()
                .getAttribute(Constants.SYS_USER);
        Ensure.that(admin).isNotNull("-1");
        return admin.getLoginName();
    }

    public ShopDto getLoginUserShop() {
        ShopDto shopDto = (ShopDto) SecurityUtils.getSubject().getSession().getAttribute(Constants.BASE_SHOP);
        Ensure.that(shopDto).isNotNull("-1");
        return shopDto;
    }

    public String getLoginUserShopName() {
        SysUserAdminDto admin = (SysUserAdminDto) SecurityUtils.getSubject().getSession()
                .getAttribute(Constants.SYS_USER);
        Ensure.that(admin).isNotNull("-1");
        ShopDto dto = shopServiceApi.findShopById(admin.getShopId());
        if (dto == null)
            return admin.getLoginName();
        else
            return dto.getName();
    }

    public Long getLoginUserID() {
        return UserUtil.getCurrentUser().getId();
    }

    public String getLoginUserPhone() {
        return UserUtil.getCurrentUser().getPhone();
    }

    /**
     * 取厂商id
     */
    public Long getShopId() {
        Ensure.that(UserUtil.getCurrentUser()).isNotNull("-1");
        return UserUtil.getCurrentUser().getShopId();
    }

    /**
     * 获取当前商户操作的店铺id
     */
    public StoreDto getStoreIdAndName(BusinessType.ShopType shopType) {
        Ensure.that(UserUtil.getCurrentUser()).isNotNull("-1");
        StoreDto storeDto = new StoreDto();
        storeDto.setCategoryId(shopType.getCode());
        storeDto.setShopId(UserUtil.getCurrentUser().getShopId());
        storeDto = storeServiceApi.selectByShopIdAndCategoryId(storeDto);
        Ensure.that(storeDto).isNotNull("00120004");
        return storeDto;
    }

    /**
     * 判断是否商家
     */
    public Long getShopId2() {
        Ensure.that(UserUtil.getCurrentUser()).isNotNull("-1");
        return UserUtil.getCurrentUser().getShopId() == 0 ? null : UserUtil.getCurrentUser().getShopId();
    }

    /**
     * 判断是否商家：true 是
     */
    public Boolean isShop() {
        Ensure.that(UserUtil.getCurrentUser()).isNotNull("-1");
        return UserUtil.getCurrentUser().getShopId() != 0 ? true : false;
    }

    public String getLoginUserRoleIds() {
        Ensure.that(UserUtil.getCurrentUser()).isNotNull("-1");
        String roles = String.valueOf(SecurityUtils.getSubject().getSession().getAttribute(Constants.SYS_USER_ROLE));
        return roles;
    }

    public String getLoginUserRoleNames() {
        Ensure.that(UserUtil.getCurrentUser()).isNotNull("-1");
        String roles;
        roles = String.valueOf(SecurityUtils.getSubject().getSession().getAttribute(Constants.SYS_USER_ROLE));
        Ensure.that(roles).isNotNull("-1");
        String[] roleIds = roles.split(",");
        String roleNames = "";
        for (int i = 0; i < roleIds.length; i++) {
            SysRoleDto sysRoleDto;
            sysRoleDto = sysRoleServiceApi.selectById(Long.parseLong(roleIds[i]));
            Ensure.that(sysRoleDto).isNotNull("-1");
            if (i == 0) {
                roleNames += sysRoleDto.getRlname();
            } else {
                roleNames += "," + sysRoleDto.getRlname();
            }
        }
        return roleNames;
    }

    /**
     * 判断当前用户是否为超管 或者平台管理员
     *
     * @return
     */
    public Boolean isAdmin() {
        return getSysRoleTypes().contains(BusinessType.SysRoleType.SYS.getCode().toString()) || getSysRoleTypes().contains(BusinessType.SysRoleType.PLATFORM.getCode().toString());
    }

    /**
     * 判断当前用户角色是否为商家旅游创客
     *
     * @return
     */
    public Boolean isTrip() {
        if (getSysRoleTypes().contains(BusinessType.SysRoleType.SHOP.getCode().toString())) {
            List<String> roleList = new ArrayList(Arrays.asList(getLoginUserRoleIds().split(",")));
            return roleList.contains(String.valueOf(BusinessType.RoleType.TRIP.getCode()));
        } else
            return false;
    }

    /**
     * 判断当前用户是否为 运营
     *
     * @return
     */
    public Boolean isBase() {
        return getSysRoleTypes().contains(BusinessType.SysRoleType.OPERATION.getCode().toString());
    }

    public List<String> getSysRoleTypes() {
        Ensure.that(UserUtil.getCurrentUser()).isNotNull("-1");
        Object o = SecurityUtils.getSubject().getSession().getAttribute(Constants.SYS_USER_ROLE_TYPE);
        Ensure.that(o).isNotNull("-1");
        String roles = String.valueOf(o);
        List<String> list = new ArrayList<>();
        if (roles != null) {
            list = Arrays.asList(roles.split(","));
        }
        return list;
    }

    /**
     * 获取商城板块ID字符串
     *
     * @return
     */
    public String getModuleIds() {
        StringBuffer roleIds = new StringBuffer();
        List roleList = Arrays.asList(getLoginUserRoleIds().split(","));
//		if (roleList.contains(BusinessType.RoleType.CREATION.getCode()))
//			roleIds.append(String.valueOf(BusinessType.ShopType.CREATION.getCode())).append(",");
//		if (roleList.contains(BusinessType.RoleType.CREATIVE.getCode()))
//			roleIds.append(String.valueOf(BusinessType.ShopType.CREATIVE.getCode())).append(",");
        if (roleList.contains(String.valueOf(BusinessType.RoleType.OUT_DOOR.getCode())))
            roleIds.append(String.valueOf(BusinessType.ShopType.OUT_DOOR.getCode())).append(",");
        if (roleList.contains(String.valueOf(BusinessType.RoleType.INTEGRAL.getCode())))
            roleIds.append(String.valueOf(BusinessType.ShopType.INTEGRAL.getCode())).append(",");
        return roleIds.length() > 1 ? roleIds.toString().substring(0, roleIds.length() - 1) : null;
    }

    /**
     * 获取商城板块
     *
     * @return
     */
    public List<BusinessType.ShopType> getModule() {
        List<BusinessType.ShopType> shops = new ArrayList<>();
        List<String> roleList = new ArrayList(Arrays.asList(getLoginUserRoleIds().split(",")));
        if (roleList.contains(String.valueOf(BusinessType.RoleType.CREATION.getCode()))) {
//			shops.add(BusinessType.Shop.CREATION);
        }
        if (roleList.contains(String.valueOf(BusinessType.RoleType.CREATIVE.getCode()))) {
//			shops.add(BusinessType.Shop.CREATIVE);
        }
        if (roleList.contains(String.valueOf(BusinessType.RoleType.OUT_DOOR.getCode())))
            shops.add(BusinessType.ShopType.OUT_DOOR);
        if (roleList.contains(String.valueOf(BusinessType.RoleType.INTEGRAL.getCode())))
            shops.add(BusinessType.ShopType.INTEGRAL);
        return shops;
    }

    /**
     * 获取商城板块
     *
     * @return
     */
    public List<BusinessType.ShopType> getModule(Long code) {
        List<BusinessType.ShopType> shops = new ArrayList<>();
        if (code == null)
            return shops;
//		if (BusinessType.ShopType.CREATION.getCode().equals(code))
//			shops.add(BusinessType.ShopType.CREATION);
//		if (BusinessType.ShopType.CREATIVE.getCode().equals(code))
//			shops.add(BusinessType.ShopType.CREATIVE);
        if (BusinessType.ShopType.OUT_DOOR.getCode().equals(code))
            shops.add(BusinessType.ShopType.OUT_DOOR);
        if (BusinessType.ShopType.INTEGRAL.getCode().equals(code))
            shops.add(BusinessType.ShopType.INTEGRAL);
        return shops;
    }

    /**
     * 获取商城板块
     *
     * @return
     */
    public String getOnlyModule() {
        List<String> roleList = new ArrayList(Arrays.asList(getLoginUserRoleIds().split(",")));
        StringBuffer sbf = new StringBuffer();
//		if (roleList.contains(String.valueOf(BusinessType.RoleType.CREATION.getCode().toString())))
//			return BusinessType.ShopType.CREATION.getCode().intValue();
//		else if (roleList.contains(String.valueOf(BusinessType.RoleType.CREATIVE.getCode().toString())))
//			return BusinessType.ShopType.CREATIVE.getCode().intValue();
//		else
        /* 商家可能及时积分商城又是户外商家的商家   可能关联多个商家角色模块 允许多商品模块分类添加商品*/
        if (roleList.contains(String.valueOf(BusinessType.RoleType.OUT_DOOR.getCode().toString()))) {
            sbf.append(BusinessType.ShopType.OUT_DOOR.getCode().toString());
            sbf.append(",");
        }
        if (roleList.contains(String.valueOf(BusinessType.RoleType.INTEGRAL.getCode().toString()))) {
            sbf.append(BusinessType.ShopType.INTEGRAL.getCode().toString());
            sbf.append(",");
        }
        if (sbf.length() > 0) {
            return sbf.substring(0, sbf.length() - 1).toString();
        }
        return null;
    }

    /**
     * 获取商城板块分类ID
     *
     * @return
     */
    public Integer getCategoryId() {
        Long category = null;
        List roleList = Arrays.asList(getLoginUserRoleIds().split(","));
//		if (roleList.contains(String.valueOf(BusinessType.RoleType.CREATION.getCode())))
//			category = BusinessType.ShopType.CREATION.getCode();
//		if (roleList.contains(String.valueOf(BusinessType.RoleType.CREATIVE.getCode())))
//			category = BusinessType.ShopType.CREATIVE.getCode();
        if (roleList.contains(String.valueOf(BusinessType.RoleType.OUT_DOOR.getCode())))
            category = BusinessType.ShopType.OUT_DOOR.getCode();
        if (roleList.contains(String.valueOf(BusinessType.RoleType.INTEGRAL.getCode())))
            category = BusinessType.ShopType.INTEGRAL.getCode();
        return category == null ? null : category.intValue();
    }

    /**
     * @Author:liyx
     * @Description:发送验证码 41-后台注册  3-找回密码
     * @Date:2017/8/8 9:44
     */
    public Boolean sendAuthInfo(String account, Integer type) {
        Pattern p = Pattern.compile("^((15[0-9])|(18[0-9])|(17[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        Matcher m = p.matcher(account);
        if (!m.matches()) {
            String nullObj = null;
            Ensure.that(nullObj).isNotNull("00001029");
        }
        SendSmsDTO ssDTO = new SendSmsDTO();
        ssDTO.setAuthTarget(account);
        Integer typeValue = new Integer(1);
        if (type.intValue() == 41) {
//			if(sysUserAdminServiceApi.selectByPhone(account)!=null){
//				String nullObj = null;
//				Ensure.that(nullObj).isNotNull("00001026");
//			}
            typeValue = BusiTypeEnum.SYS_REGISTER_VERIFY.getVal();
        } else if (type.intValue() == 3) {
            typeValue = BusiTypeEnum.FIND_PWD_VERIFY.getVal();
        }
        ssDTO.setAuthType(typeValue);
        ssDTO.setWay(com.lzy.sms.constants.CommonConstants.MediaWay.PHONE);
        Boolean bool = msgCodeApi.sendCode(ssDTO, null);
        return bool;
    }

    /**
     * @Author:liyx
     * @Description:校验验证码
     * @Date:2017/8/8 9:44
     */
    public boolean verifyAuthInfo(String account, String code, Integer type) {
        CodeDTO codeDTO = new CodeDTO();
        codeDTO.setAuthTarget(account);
        Integer typeValue = new Integer(1);
        if (type.intValue() == 41) {
            typeValue = BusiTypeEnum.SYS_REGISTER_VERIFY.getVal();
        } else if (type.intValue() == 3) {
            typeValue = BusiTypeEnum.FIND_PWD_VERIFY.getVal();
        }
        codeDTO.setAuthType(typeValue);
        codeDTO.setWay(com.lzy.sms.constants.CommonConstants.MediaWay.PHONE);
        codeDTO.setAuthCode(code);
        Boolean bool = msgCodeApi.verifyAuthInfo(codeDTO);
        return bool;
    }

    @RequestMapping(value = "/refresh/token", method = RequestMethod.GET)
    @ResponseBody
    public Result getToken() {
        Object token = SecurityUtils.getSubject().getSession().getAttribute("token");
        return token == null ? new Result() : new Result(token);
    }

    /**
     * 文件下载
     *
     * @param request
     * @param response
     * @param filePath     文件物理路径
     * @param fileRealName 文件真实名字
     * @return
     */
    public ModelAndView downloadFile(HttpServletRequest request, HttpServletResponse response, String filePath, String fileRealName) {
        if (StringUtils.isBlank(filePath) || !(new File(filePath)).exists()) {
            try (PrintWriter out = response.getWriter()) {
                out.println("文件【" + filePath + "】不存在");
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            response.setContentType("text/html;charset=UTF-8");
            request.setCharacterEncoding("UTF-8");

            // 获取文件名
            File file = new File(filePath);
            if (StringUtils.isBlank(fileRealName)) {
                fileRealName = file.getName();
            }
            long fileLength = file.length();

            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileRealName.getBytes("gb2312"), "ISO8859-1"));
            response.setHeader("Content-Length", String.valueOf(fileLength));

            bis = new BufferedInputStream(new FileInputStream(filePath));
            bos = new BufferedOutputStream(response.getOutputStream());

            byte[] buff = new byte[1024 * 100];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != bis) {
                    bis.close();
                }
                if (null != bos) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 参数处理
     *
     * @param categoryDtoList
     * @param model
     */
    public void paramSet(List<ItemCategoryDto> categoryDtoList, Model model) {
        categoryDtoList.forEach(categoryDto -> {
            if (categoryDto.getLevel() == 1) {
                model.addAttribute("top", categoryDto);
            }
            if (categoryDto.getLevel() == 2) {
                model.addAttribute("sec", categoryDto);
            }
            if (categoryDto.getLevel() == 3) {
                model.addAttribute("third", categoryDto);
            }
            if (categoryDto.getLevel() == 4) {
                model.addAttribute("four", categoryDto);
            }
        });
    }
}
